/**
 * 
 */
package com.leo.book.distributed.chapter04.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description: 操作原子性-不存在安全性问题
 * @author lianliang
 * @date 2017年12月18日 下午4:41:48
 */
public class CountSafe {
	public AtomicInteger count = new AtomicInteger(0);

	static class Job implements Runnable {
		private CountDownLatch countDown;
		private CountSafe countSafe;

		public Job(CountSafe count, CountDownLatch countDown) {
			this.countSafe = count;
			this.countDown = countDown;
		}

		@Override
		public void run() {
			boolean isSuccess = false;
			while(!isSuccess) {
				int val = countSafe.count.get();
				isSuccess = countSafe.count.compareAndSet(val, val+1);
			}
			countDown.countDown();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDown = new CountDownLatch(1500);
		CountSafe count = new CountSafe();
		ExecutorService pool = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 1500; i++) {
			pool.execute(new Job(count, countDown));
		}
		countDown.await();
		System.out.println(count.count);
		pool.shutdown();
	}
}
